package com.qf.servlet;

import com.qf.domain.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * projectName:book1
 * author:dongliuyang
 * time:2022/11/22 10:30
 * description:
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");

        if (StringUtils.isEmpty(username)) {
            response.getWriter().write("用户名不能为空");
            return;
        }
        if(StringUtils.isEmpty(password)){
            response.getWriter().write("密码不能为空");
            return;
        }
        if(StringUtils.isEmpty(vcode)){
            response.getWriter().write("验证码不能为空");
            return;
        }
        String code=(String) request.getSession().getAttribute("code");
        if (!code.equalsIgnoreCase(vcode)){
            response.getWriter().write("验证码输入有误");
            return;
        }

        try {
            UserService userService=new UserServiceImpl();
            User user=userService.login(username,password);

            HttpSession session=request.getSession();
            session.setAttribute("user",user);
            response.sendRedirect("booklistpage");
        } catch (Exception e) {
           e.printStackTrace();
           response.sendRedirect("message.html");
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
